package com.weixing.mall.provider.controller.ads;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.support.auth.SysInfo;
import com.weixing.mall.provider.model.domain.MediaOrderdRecord;
import com.weixing.mall.provider.model.domain.MediaPlatform;
import com.weixing.mall.provider.model.dto.ads.MediaAdvertSingChgDto;
import com.weixing.mall.provider.model.dto.ads.MediaAdvertsingDto;
import com.weixing.mall.provider.model.enums.AppointmentEunm;
import com.weixing.mall.provider.model.enums.IsPageSiteEunm;
import com.weixing.mall.provider.model.query.MediaAdvertsingQuery;
import com.weixing.mall.provider.model.vo.ads.MediaAdvertsingVo;
import com.weixing.mall.provider.model.vo.excel.MediaAdvertsingED;
import com.weixing.mall.provider.service.IMediaAdvertsingService;
import com.weixing.mall.provider.service.IMediaOrderdRecordService;
import com.weixing.mall.provider.service.IMediaPlatformService;
import com.weixing.mall.provider.support.excel.EasyExcelUtil;
import com.weixing.mall.provider.support.excel.ads.AdsExcalData;
import com.weixing.mall.provider.support.excel.ads.AdsImportListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName MediaAdvertsingController
 * @Description TODO <br/>
 * @Author gjq
 * @Modified By:
 * @Date 2019/8/16
 * @Version 1.0
 **/
@RestController
@RequestMapping("mediaAdvertsing")
@Api(value = "媒体广告APi", tags = "媒体广告")
public class MediaAdvertsingController extends BaseController {

    @Autowired
    private IMediaAdvertsingService mediaAdvertsingService;

    @Autowired
    private IMediaOrderdRecordService mediaOrderdRecorService;
    @Autowired
    private IMediaPlatformService mediaPlatformService;

    @ApiOperation(value = "加载媒体广告列表")
    @GetMapping("")
    public Result list(@SysInfo SysAuth auth, MediaAdvertsingQuery mediaAdvertsingQuery) {
        return ResultUtil.success(mediaAdvertsingService.selectOfPage(initMpPage(), mediaAdvertsingQuery, auth.getUid()));
    }

    @ApiOperation(value = "加载媒体广告列表")
    @GetMapping("listExcel")
    public void listExcel(@SysInfo SysAuth auth, MediaAdvertsingQuery mediaAdvertsingQuery, HttpServletResponse response) {
        IPage<MediaAdvertsingVo> list = mediaAdvertsingService.selectOfPage(initMpPage(), mediaAdvertsingQuery, auth.getUid());
        List<MediaAdvertsingED> list2 = Lists.newArrayList();
        list.getRecords().forEach(m -> {
            MediaAdvertsingED ma = new MediaAdvertsingED();
            BeanUtils.copyProperties(m, ma);
            list2.add(ma);
        });
        try {
            EasyExcelUtil.writeExcel(response, MediaAdvertsingED.class, list2, "媒体广告列表");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "查询媒体广告")
    @GetMapping("getList")
    public Result getList(MediaAdvertsingQuery mediaAdvertsingQuery) {
        return ResultUtil.success(mediaAdvertsingService.getList(mediaAdvertsingQuery));
    }

    @ApiOperation(value = "通过id查看媒体平台广告")
    @GetMapping("selectMediaAdvertsing/{id}")
    public Result selectMediaAdvertsing(@PathVariable("id") Long id) {
        return ResultUtil.success(mediaAdvertsingService.getById(id));
    }

    @ApiOperation(value = "二期批量选择进行保存媒体广告信息")
    @PostMapping("saveBatch")
    @NoRepeatSubmit
    public Result saveBatch(@Validated MediaAdvertsingDto mediaAdvertsingDto) {
        List<Long> ids = mediaAdvertsingDto.getIds();
        if (ids.size() > 100) {
            ResultUtil.error("数量不允许打过100条");
        }
        for (Long id : ids) {
            mediaAdvertsingDto.setPlatform(id);
            MediaPlatform mediaPlatform = mediaPlatformService.getById(id);
            mediaAdvertsingDto.setMediaType(mediaPlatform.getMediaType());
            mediaAdvertsingDto.setDirector(mediaPlatform.getDirector());
            mediaAdvertsingDto.setPageSite(IsPageSiteEunm.TYPE1);
            mediaAdvertsingDto.setPrice(mediaPlatform.getPriceOut());

            mediaAdvertsingService.save(mediaAdvertsingDto);
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "二期批量发布单个媒体广告信息")
    @PostMapping("saveBatchNumber")
    @NoRepeatSubmit
    public Result saveBatchNumber(@Validated MediaAdvertsingDto mediaAdvertsingDto) {
        Integer ids = mediaAdvertsingDto.getNumber();
        if (ids.intValue() > 100) {
            return ResultUtil.error("数量不允许打过100条");
        }
        for (int i = 0; i < ids.intValue(); i++) {
            mediaAdvertsingService.save(mediaAdvertsingDto);
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "保存媒体广告信息")
    @PostMapping("save")
    @NoRepeatSubmit
    public Result save(@Validated MediaAdvertsingDto mediaAdvertsingDto) {
        mediaAdvertsingService.save(mediaAdvertsingDto);
        return ResultUtil.success();
    }

    @ApiOperation(value = "改变广告状态")
    @PostMapping("changeStaus")
    public Result changeStaus(@Validated MediaAdvertSingChgDto mediaAdvertSingChgDto) {
        mediaAdvertsingService.changeStaus(mediaAdvertSingChgDto.getId(), mediaAdvertSingChgDto.getStaus().getValue());
        return ResultUtil.success();
    }

    @ApiOperation(value = "媒体广告编辑模板导出")
    @GetMapping("template")
    public void excel(MediaAdvertsingQuery mediaAdvertsingQuery, HttpServletResponse response) {
        List<MediaAdvertsingVo> list = mediaAdvertsingService.selectList(mediaAdvertsingQuery);
        if (list == null || list.size() == 0) {
            throw new BusinessException("无可用数据导出");
        }
        List<AdsExcalData> importList = Lists.newArrayList();
        list.forEach(mav -> {
            AdsExcalData aed = new AdsExcalData();
            aed.setId(mav.getId());
            aed.setMediaTypeName(mav.getMediaTypeName());
            aed.setPlatformName(mav.getPlatformName());
            aed.setTitle(mav.getArticleTitle());
            aed.setReadNum(mav.getReadAmount());
            aed.setFans(mav.getFans());
            aed.setLaunchDate(mav.getLaunchDate());
            importList.add(aed);
        });
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("媒体广告编辑模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AdsExcalData.class).sheet("sheet1").doWrite(importList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("广告数据导入")
    @PostMapping("importAds")
    public Result importAds(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), AdsExcalData.class, new AdsImportListener(mediaAdvertsingService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success();
    }

    @ApiOperation("删除代理商全部取消的广告")
    @GetMapping("delCalelAds/{id}")
    public Result delCalelAds(@PathVariable Long id) {
        List<MediaOrderdRecord> mediaOrderdRecordList = mediaOrderdRecorService.list(new QueryWrapper<MediaOrderdRecord>().eq("ad_id", id));
        for (MediaOrderdRecord record : mediaOrderdRecordList) {
            if (record.getStatus().intValue() != AppointmentEunm.STATUS5.getValue().intValue()) {
                return ResultUtil.error("存在未取消订单，不允许删除");
            }
        }
        mediaAdvertsingService.removeById(id);
        return ResultUtil.success();
    }
}
